﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace BaseHelper.Base
{
    public class JsonHashtableHelper
    {
        public static string HashtableToList(Hashtable[] hts)
        {
            if (hts == null) return "";
            string listCollect = "";
            foreach (Hashtable ht in hts)
            {
                listCollect += HashtableToList(ht) + ",";
            }
            if (listCollect != "")
                listCollect = listCollect.Substring(0, listCollect.Length - 1);

            return listCollect;
        }

        public static string HashtableToList(Hashtable ht)
        {
            if (ht == null) return "";
            string list = "";
            foreach (string key in ht.Keys)
            {
                if (ht[key] is Hashtable[])
                {
                    list += "\"" + key + "\":[" + HashtableToList((Hashtable[])ht[key]) + "],";
                }
                else if (ht[key] is List<Hashtable>)
                {
                    List<Hashtable> lt = (List<Hashtable>)ht[key];
                    list += "\"" + key + "\":[" + HashtableToList(lt.ToArray()) + "],";
                }
                else if (ht[key] is Hashtable)
                {
                    list += "\"" + key + "\":" + HashtableToList((Hashtable)ht[key]) + ",";
                }
                else
                {
                    if (ht[key] == null)
                    {
                        list += "\"" + key + "\":\"\",";
                    }
                    else if (ht[key].ToString().IndexOf("[") == 0 && (ht[key].ToString().LastIndexOf("]") == ht[key].ToString().Length - 1))
                        list += "\"" + key + "\":" + ht[key].ToString() + ",";
                    else
                        //忘记是哪里出现\\问题，这里先屏蔽下
                        list += "\"" + key + "\":\"" + ht[key].ToString().Replace("\\", "\\\\") + "\",";
                    //list += "\"" + key + "\":\"" + Tools.StrToUrl(ht[key].ToString()) + "\",";
                }
            }

            if (list != "")
                list = list.Substring(0, list.Length - 1);

            return "{" + list + "}";
        }

    }
}
